﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPoco;
using Creative85.Framework.Data;
using Creative85.Framework.Utilities;

namespace Project32CHE.Biz.Goods
{
    public static class GoodsService
    {
        /// <summary>
        /// 根据仓库查出的仓库列表
        /// </summary>
        /// <param name="ShopID"></param>
        /// <param name="UnionID"></param>
        /// <param name="StorageID"></param>
        /// <param name="Key"></param>
        /// <returns></returns>
        public static List<Dictionary<string, object>> GetGoodsByStorage(Guid ShopID, Guid UnionID, Guid StorageID, string key)
        {
            var sql = new SqlBuilder();
            var sqlTpl = sql.AddTemplate(@"
select top 1 g.*,s.Qty from GoodsInfo g with(nolock) left join
(select SUM(Qty) as Qty ,GoodsID from StorageItem with(nolock)  where storageid=@0 group by GoodsID ) s on g.ID=s.GoodsID 
 where /**where**/ /**orderby**/", StorageID);
            sql.Where("g.UnionID=@0 and g.Shopid=@1 and g.IsDeleted=0", UnionID, ShopID);
            sql.Where("(g.GoodsCode = @0)", key);
            var ret = Db.Instance.Page<Dictionary<string, object>>(1, 100, sqlTpl);
            return ret.Items;
        }
       
        /// <summary>
        /// 根据编码获取商品记录
        /// </summary>
        /// <param name="unionId"></param>
        /// <param name="shopId"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static Model.Goods Get(Guid unionId, Guid shopId, string code)
        {
            return Db.Instance.Query<Model.Goods>().Where(x => x.IsDeleted == false).Where(x => (x.UnionID == unionId && x.ShopID == shopId && x.GoodsCode == code)).SingleOrDefault();
        }
        /// <summary>
        /// 根据商品ID获取商品记录
        /// </summary>
        /// <param name="GoodsId"></param>
        /// <returns></returns>
        public static Model.Goods Get(Guid GoodsId)
        {
            return Db.Instance.SingleById<Model.Goods>(GoodsId);
        }

    }
}
